package com.liwy3.account.controller;

import com.liwy3.account.entity.SysUserEntity;
import com.liwy3.account.mapper.SysUserMapper;
import com.liwy3.client.RedisClient;
import com.liwy3.common.domain.R;
//import com.liwy3.configuration.RedisConfig;
import lombok.SneakyThrows;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

/**
 * Copyright © 元气森林（北京）食品科技集团有限公司. All rights reserved.
 *
 * @Description:
 * @author: Crazy4J
 * @date: 2022年02月24日 15:39
 * @version: V1.0
 */
@RestController
public class AccountController {



    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private RedisClient redisClient;
    @Resource
    private RedissonClient redissonClient;

    @PostMapping("/account/add")
    public R<?> add(@RequestParam("amount") BigDecimal amount) {

        redisClient.setCacheObject("k1111", "v11111");
        System.out.println("账户加钱:" + amount);
        SysUserEntity sysUserEntity = sysUserMapper.selectById(1L);
        sysUserEntity.setMerId("10090");
        sysUserMapper.updateById(sysUserEntity);

        return R.ok();
    }

    @PostMapping("/account/add2")
    public R<?> add2(@RequestParam("amount") BigDecimal amount) {
        System.out.println("账户加钱:" + amount);
        SysUserEntity sysUserEntity = sysUserMapper.selectById(1L);
        sysUserEntity.setMerId("10091");
        sysUserMapper.updateById(sysUserEntity);

        return R.ok();
    }

    @PostMapping("/test")
    public void test() {
        RLock lock = redissonClient.getLock("order:o123");
        boolean flag = false;
        try {
            //
            System.out.println(Thread.currentThread() + "=============try获取锁============");
            flag = lock.tryLock(1L, 10L, TimeUnit.SECONDS);
            System.out.println(Thread.currentThread() + "=============get获取到锁============" + flag);
            Thread.sleep(10000L);
            System.out.println(Thread.currentThread() + "=============execute执行业务逻辑============"+ flag);

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (flag) {
                System.out.println(Thread.currentThread() + "==============release释放锁=========================="+ flag);
                lock.unlock();
            }
        }
    }

}
